import { readFile, writeFile } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";

class TypeDeclarationGenerator {
  private readonly scriptDir: string;
  private readonly sourceFile: string;
  private readonly outputFile: string;

  constructor() {
    this.scriptDir = dirname(fileURLToPath(import.meta.url));
    this.sourceFile = resolve(this.scriptDir, "../js/environment.d.ts");
    this.outputFile = resolve(this.scriptDir, "../js/type-declarations.ts");
  }

  private escapeTemplateString(content: string): string {
    return content.replace(/`/g, "\\`").replace(/\$\{/g, "\\${");
  }

  private buildOutputContent(sourceContent: string): string {
    const header = [
      "// THIS FILE IS GENERATED BY update-type-declarations.ts",
      "// DO NOT EDIT DIRECTLY",
      "",
    ].join("\n");

    const exportStatement = `export const typeDeclarations = \`\n${this.escapeTemplateString(sourceContent)}\``;

    return `${header}\n${exportStatement}\n`;
  }

  async execute(): Promise<void> {
    try {
      const rawDeclarations = await readFile(this.sourceFile, "utf-8");
      const processedContent = this.buildOutputContent(rawDeclarations);
      await writeFile(this.outputFile, processedContent);
    } catch (error) {
      console.error("Failed to generate type declarations:", error);
      throw error;
    }
  }
}

const generator = new TypeDeclarationGenerator();
await generator.execute();
